package ftl;

import utils.FreeMarkUtil;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName CreateADEG
 * @Description 生成增删改查jave代码
 * @Author Liujt
 * @Date 2019/11/29 10:59
 **/
public class CreateADEG {

    //生成的文件名称后缀
    private static final String SERVER_TYPE_C = "Controller.java";
    private static final String SERVER_TYPE_I = "Service.java";
    private static final String SERVER_TYPE_IMPL = "ServiceImpl.java";
    //接口及服务类前缀
    private static final String INTERFACE_PRE = "I";

    //包路径
    private static final String PACKAGE_PATH = "org.cs.dp.sonar.";
    //文件保存位置
    private static final String SAVE_PATH = "C:\\Users\\Liujt\\Desktop\\test\\";
    //业务变量名
    private static final String NAME = "Device";
    //业务注释
    private static final String EXPLAIN = "设备管理";
    //作者
    private static final String AUTHOR = "Liujt";
    //时间
    private static final String DATE = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());

    public static void main(String[] args) throws IOException {
        create();
    }

    private static void create() throws IOException {
        Map param = new HashMap();
        //包路径
        param.put("packagePath", PACKAGE_PATH);
        //文件保存位置
        param.put("path", SAVE_PATH);
        //业务变量名
        param.put("name", NAME);
        //业务注释
        param.put("explain", EXPLAIN);
        //作者
        param.put("author", AUTHOR);
        //时间
        param.put("date", DATE);

        writerFile(
                SAVE_PATH,
                FreeMarkUtil.getTemplate("/controller.ftl", param),
                NAME + SERVER_TYPE_C);

        writerFile(
                SAVE_PATH,
                FreeMarkUtil.getTemplate("/interface.ftl", param),
                INTERFACE_PRE + NAME + SERVER_TYPE_I);

        writerFile(
                SAVE_PATH,
                FreeMarkUtil.getTemplate("/impl.ftl", param),
                INTERFACE_PRE + NAME + SERVER_TYPE_IMPL);

    }

    private static void writerFile(String path, String content, String name) throws IOException {

        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        } else {
            removeDir(file, name);
        }
        file = new File(path + name);
        file.createNewFile();
        Writer out = new FileWriter(file);
        out.write(content);
        out.close();
    }

    private static void removeDir(File dir, String name) {
        File[] files = dir.listFiles();
        for (File file : files) {
            if (!file.isDirectory()) {
                if (file.getName().contains(name)) {
                    System.out.println(file + ":" + file.delete());
                }
            }
            System.out.println(dir + ":" + dir.delete());
        }
    }
}
